const { resolve, join } = require('path')
const fse = require('fs-extra')
const UPLOAD_PATH = resolve(__dirname, '..', 'target')
const FileModel = require('../db/FileModel')

  // 获取文件后缀名
const getInfor = (filename, arg) => 
  arg == 'ext' ? filename.slice(filename.lastIndexOf('.')+1, filename.length) :
  filename.slice(0, filename.lastIndexOf('.'))

const resolvePost = async (req) =>
  new Promise(reslove => {
    let chunk = ''
    req.on('data', data => {
      chunk += data
    })
    req.on('end', _ => {
      reslove(JSON.parse(chunk))
    })
  }).catch(err => console.log(err))

const deletefile = async (fileDir, file) => 
  new Promise(resolve => {
    fse.unlink(`${fileDir}/${file}`)
    resolve()
  })

module.exports = class {
  async getfiles(req, res) {
    // console.log(req.query);
    // const path = resolve(__dirname, '..', req.query.filename)
    const [,_filename] = req.query.filename.split('target')
    const path = join(UPLOAD_PATH, '/', _filename)
    if (!await fse.exists(path)) {
      res.send({
        type: 'error',
        message: '找不到文件夹'
      })
      return
    }
    const files = await fse.readdir(path)
    // 获取时间 文件名
    console.log(files);
    if (files.length == 0) {
      // console.log('文件夹为空');
      res.send({
        type: 'warning',
        message: '文件夹为空'
      })
      return
    }
    let files_data = []
    for (let i = 0; i < files.length; i++ ){
      // let { ctime, size } = await fse.stat(`${UPLOAD_PATH}/${files[i]}`)
      let stat = await fse.stat(`${path}/${files[i]}`)
      if (stat.isDirectory()) {
        let { ctime } = stat
        files_data.push({
          filename: files[i],
          isDirectory: true,
          date: ctime,
          size: null
        })
        continue
      } else {
        let { ctime, size } = stat
        let date = new Date(ctime).toLocaleString()
        let filehash = getInfor(files[i])
        let { filename } = await FileModel.findOne({ filehash })
        let type = getInfor(files[i], 'ext') // 文件类型
        files_data.push({
          filename,
          filehash,
          date,
          size,
          type
        })
      }
    }
    // console.log(files_data);
    res.send(files_data);
  }
  async addfile (req, res) {
    const {filename, path} = await resolvePost(req)
    const targetpath = join(UPLOAD_PATH, '.', path)
    // const filepath = join(targetpath, '.', filename)
    fse.mkdirSync(`${targetpath}/${filename}`)
    res.send('ok')
  }
  // 删除文件/文件夹
  async deletefile (req, res) {
    const {file, path} = await resolvePost(req)
    const filepath = join(UPLOAD_PATH, '/', path)
    // console.log(filepath);
    // console.log(file, path);
    const ext = getInfor(file.filename, 'ext')
    // console.log(ext);
    if (!file.isDirectory) {
      await fse.unlink(`${filepath}/${file.filehash}.${ext}`)
      // await FileModel.deleteMany({filehash: file.filehash})
    } else {
      const fileDir = join(filepath, '/', file.filename)
      const files = fse.readdirSync(fileDir)
      let filelist = []
      files.forEach(async (file) => {
        filelist.push(deletefile(fileDir, file))
      })
      Promise.all(filelist).then(_ => {
        fse.rmdirSync(fileDir);
      })
    }
    res.send({
      success: true
    })
  }

  // 下载
  async downloadfile (req, res) {
    const {filename, filepath, filehash} = req.query
    console.log(req.query);
    let ext = getInfor(filename,'ext')
    const downloadDir = join(UPLOAD_PATH, filepath, `${filehash}.${ext}`)
    res.download(downloadDir, filename)
  }
}


// app.get('/download', (req, res) => {
//   req.query.file ? res.download(`./target/${req.query.file}`) : res.send({success: false})
// })

